package cn.mabach.business.service.impl;


import cn.mabach.DTO.PageUtils;
import cn.mabach.DTO.RS;
import cn.mabach.business.dao.AdDao;
import cn.mabach.business.entity.AdEntity;
import cn.mabach.business.service.AdService;
import cn.mabach.utils.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

import static cn.mabach.consts.EhCache.ADEHCACHE;


@RestController
public class AdServiceImpl extends ServiceImpl<AdDao, AdEntity> implements AdService {

    @Override
    public RS<PageUtils> queryPage(@RequestParam Map<String, Object> params) {
        IPage<AdEntity> page = this.page(
                new Query<AdEntity>().getPage(params),
                new QueryWrapper<AdEntity>()
        );
        if (page==null){
            return RS.error();
        }
        return RS.ok(new PageUtils(page));
    }





    @Override
    public RS<AdEntity> getByIdE(@RequestParam("id") Integer id) {
            AdEntity res = this.getById(id);
        if (res==null){
            return RS.error();
        }
        return RS.ok(res);
    }

    @Override
    public RS saveE(@RequestBody AdEntity entity) {
        boolean b = this.save(entity);
        if (!b){
            return RS.error();
        }
        return RS.ok();
    }

    @Override
    public RS updateByIdE(@RequestBody AdEntity entity) {
        boolean b = this.updateById(entity);
        if (!b){
            return RS.error();
        }
        return RS.ok();
    }

    @Override
    public RS removeByIdsE(@RequestBody List<Integer> ids) {
        boolean b = this.removeByIds(ids);
        if (!b){
            return RS.error();
        }
        return RS.ok();
    }

    @Override
    @Cacheable(cacheNames = ADEHCACHE,key = "'adEhCache'")
    public RS<List<AdEntity>> findByPosition(@RequestParam("position") String position) {
        List<AdEntity> list = this.list(new QueryWrapper<AdEntity>().eq("position", position).eq("status", "1")
                .lt("start_time", LocalDateTime.now()).gt("end_time",LocalDateTime.now()));

        return RS.ok(list);
    }



}